package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1/file/")
public class UploadController {

    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        /*
            1.将图片保存到服务器 d:/files/2025/03/11/xxx.jpg
            2.返回响应{"state":2000,"message":"操作成功","data":"/2025/03/11/xxx.jpg"}
              前端：http://localhost:8080/2025/03/11/xxx.jpg
         */
        //1.处理文件名
        String filename = file.getOriginalFilename(); //xxx.jpg
        String suffix = filename.substring(filename.lastIndexOf(".")); //.jpg
        // UUID.randomUUID()生成一个全球唯一的字符串,作为文件名;
        filename = UUID.randomUUID() + suffix; //d248f2e2-1387-48ba-b26f-5a6a4846de6e.jpg

        //2.处理路径
        String dirPath = "d:/files";
        // 生成日期格式的路径,为了后期文件检索的效率, /2025/03/11/
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date()); // /2025/03/11/

        //创建目录: d:/files/2025/03/11/
        File dirFile = new File(dirPath + datePath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }

        //保存文件: d:/files/2025/03/11/d248f2e2-1387-48ba-b26f-5a6a4846de6e.jpg
        String filePath = dirPath + datePath + filename;
        file.transferTo(new File(filePath));

        //{"state":2000,"message":"操作成功","data":"/2025/03/11/xxx.jpg"}
        //未来前端访问:http://localhost:8080/2025/03/11/xxx.jpg 访问到图片资源,渲染到页面上
        return JsonResult.ok(datePath + filename);
    }
}







